#!/usr/bin/env bash
# Copyright (C) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in project root for information.

. "$(dirname "${BASH_SOURCE[0]}")/../../runme"

PRDIR="$BASEDIR/.build-pr"
F="$PRDIR/build-pr/$(basename ${BASH_SOURCE[0]})"

if [[ "${BASH_SOURCE[0]}" != "$F" ]]; then
  if [[ -x "$F" ]]; then exec "$F"; fi; exit
fi

@ "shared.sh"

ICONS_URL="https://$MAIN_STORAGE.blob.core.windows.net/icons"
icon="$ICONS_URL/Robot"
case "${AGENT_JOBSTATUS,,}" in
  ( succeeded ) icon+="2.svg"; box="![PASS]($icon) Pass";       state="success" ;;
  ( canceled  ) icon+="1.svg"; box="![CANCEL]($icon) Canceled"; state="error"   ;;
  ( failed    ) icon+="0.svg"; box="![FAIL]($icon) Fail";       state="failure" ;;
  ( *         ) icon+="1.svg"; box="![$AGENT_JOBSTATUS]($icon) Unknown"; state="error" ;;
esac

if [[ "$BUILDPR" = "" ]]; then
  _ az storage blob copy start --account-name "$MAIN_STORAGE" \
       --destination-container "icons" --destination-blob "BuildStatus.png" \
       --source-uri "$icon"
  exit
fi

text="The build has ${AGENT_JOBSTATUS,,}."; more_text=""
post_status "$state" "$text"
delete_comment
if [[ "$state" = "success" && -r "$BUILD_ARTIFACTS/Build.md" ]]; then
  more_text="$(< "$BUILD_ARTIFACTS/Build.md")"
fi
post_comment "$box! — $text" "$more_text"
